// const BASE_URL = 'https://leoweb.cloud'
const BASE_URL = 'https://wap.wkxz.net/'

const getHeader = () => {
	const token = uni.getStorageSync('accessToken')
	let header = {}
	if(token.length!==0){
		header = Object.assign({'authorization':token},header)
	}
	return header
}

class WYRequest {
	request(method: any,url: string,params={}){
		return new Promise((resolve,reject) => {
			uni.request({
				method,
				url:BASE_URL+url,
				data:params,
				header:getHeader(),
				success:(res) => {
					if(res.statusCode === 200){
						resolve(res.data)
					}else if(res.statusCode === 401){
						this.request(method,url,params).then(res => {
							resolve(res.data)
						})						
					}else if(res.statusCode === 4001){
						console.log('身份令牌失效');
						uni.reLaunch({ url: '/pages/login/login' });
						reject(new Error(res.statusCode))
					}
					else{
						reject(new Error(res.statusCode))
					}
				},
				fail:(err) => {
					let errorMessage = ''
					
					if(err.errMsg.includes('timeout')){
						errorMessage = '请求超时，请稍后重试'
					} else if(err.errMsg.includes('abort')){
						errorMessage = '请求数据错误，请重试'
					} else {
						errorMessage = '网络请求错误，请检查网络连接'
					}
					reject(new Error(errorMessage))
				}
			})
		})
	}
	
	get(url:string,params={}){
		return this.request('get',url,params)
	}
	post(url:string,params={}){
		return this.request('post',url,params)
	}
}

const wyRequest = new WYRequest()

export default wyRequest